<template>
  <div class="book-detail">
    <t-card :bordered="false" class="content-card">
      <template #title>
        <t-space size="0">
          <div class="drawer-head" style="height: 36px;">
            <p class="chevron-left" @click="back">
              <icon-font name="chevron-left" size="18px"/>
            </p>
          </div>
          <div>
            <t-space size="18px">
              <h2 class="card-title">{{ storeInfo.name }}</h2>
              <t-dropdown :min-column-width="80" placement="bottom" trigger="click">
                <template #dropdown>
                  <t-dropdown-menu>
                    <t-dropdown-item v-for="(item, index) in storeList" :key="index" @click="changeStore(item)">
                      <p>{{ item.name }}</p>
                    </t-dropdown-item>
                  </t-dropdown-menu>
                </template>
                <icon-font name="chevron-down-circle" style="line-height: 22px"/>
              </t-dropdown>
            </t-space>
            <div style="display: flex;align-items: center;gap: 16px">
              <p class="card-sub-title">库存数：
                <t-link theme="primary" hover="color" @click="goStoreDetail()">
                  {{ storeInfo.total_stock ? storeInfo.total_stock : 0 }}
                </t-link>
              </p>
              <p class="card-sub-title">入库记录：
                <t-link theme="primary" hover="color" @click="handleOption('WarehousingHistory')">
                  {{ storeInfo.rk_county ? storeInfo.rk_county : 0}}
                </t-link>
              </p>
              <p class="card-sub-title">出库记录：
                <t-link theme="primary" hover="color" @click="handleOption('OutboundHistory')">
                  {{storeInfo.ck_count ? storeInfo.ck_count : 0}}
                </t-link>
              </p>
              <p class="card-sub-title">调拨记录：
                <t-link theme="primary" hover="color" @click="handleOption('DispatchHistory')">
                  {{storeInfo.db_count ? storeInfo.db_count : 0}}
                </t-link>
              </p>
            </div>
          </div>
        </t-space>
      </template>
      <template #actions>
        <t-space size="8px">
          <t-button @click="handleWarehousing" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-warehousing" style="font-size: 24px;margin-right: 4px"></i>入库
            </p>
          </t-button>
          <t-button @click="handleOutbound" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-outbound" style="font-size: 24px;margin-right: 4px"></i>出库
            </p>
          </t-button>
          <t-button @click="handleAllocation" class="add-btn">
            <p class="flex align-center">
              <i class="iconfont icon-warehousing" style="font-size: 24px;margin-right: 4px"></i>调拨
            </p>
          </t-button>
          <!--<t-button @click="handleInventory" class="add-btn">-->
          <!--  <p class="flex align-center">-->
          <!--    <i class="iconfont icon-warehousing" style="font-size: 24px;margin-right: 4px"></i>盘点-->
          <!--  </p>-->
          <!--</t-button>-->
        </t-space>
      </template>

      <div class="filter ">
        <t-space size="12px">
          <t-input style="width: 220px;" v-model="params.key" clearable @change="getData" placeholder="搜索：产品名称">
            <template #label>
              <icon-font name="search" size="16px" style="color:#000;font-weight: bold"/>
            </template>
          </t-input>
        </t-space>
      </div>

      <div class="pt16">
        <t-table
          rowKey="id"
          :data="lists"
          :columns="columns"
          :stripe="stripe"
          :bordered="bordered"
          :hover="hover"
          :size="size"
          :max-height="maxHeight"
          :table-layout="tableLayout ? 'auto' : 'fixed'"
          :showHeader="showHeader"
          cellEmptyContent="-"
          resizable
          :loading="loading"
          @page-change="pageChange"
          :pagination="pagination"
          :selected-row-keys="selectedRowKeys"
          @select-change="handleSelectChange"
        >
          <template #title-slot-option></template>
          <template #product_thumb="{row}">
            <t-image-viewer v-if="row.product_thumb" :images="[row.product_thumb]" :closeOnEscKeydown="false">
              <template #trigger="{ open }">
                <div class="tdesign-demo-image-viewer__ui-image" @click="open">
                  <p class="prod-img">
                    <img alt="test" :src="row.product_thumb"/>
                  </p>
                  <div class="tdesign-demo-image-viewer__ui-image--hover">
                    <span><browse-icon size="1.4em"/> </span>
                  </div>
                </div>
              </template>
            </t-image-viewer>
            <p v-else class="no-img"></p>
          </template>
          <template #product_title="{row}">
            <div class="">
              <p class="item-title">{{ row.product_title }}</p>
              <p v-if="row.sn" class="item-sn">S/N:{{ row.sn }}</p>
            </div>
          </template>
          <template #total_price="{row}">
            <div class="flex align-center">
              <p>{{ row.total_price ? `￥${row.total_price}` : '-' }}</p>
            </div>
          </template>
          <template #product_selling_price="{row}">
            <div class="flex align-center">
              <p>{{ row.product_selling_price ? `￥${row.product_selling_price}` : '-' }}</p>
              <t-tooltip v-if="!row.product_selling_price" content="请到产品库设置产品的售价">
                <icon-font name="help-circle" style="margin-left: 6px"></icon-font>
              </t-tooltip>
            </div>
          </template>
          <template #option="{row}">
            <t-space size="12px">
              <t-link v-if="row.quantity > 0" theme="primary" class="edit-btn-color" hover="color"
                      @click="onOutbound(row)">出库
              </t-link>
              <t-link theme="primary" class="edit-btn-color" hover="color" @click="handleInfo(row)">详情</t-link>
              <t-popconfirm theme="danger" placement="top-right" confirm-btn="删除"
                            @confirm="handleDelete($event, row)">
                <template #content>
                  <div class="popconfirm-body">
                    <h3 class="popconfirm-title">确认删除？</h3>
                    <p>删除后数据将不可恢复！是否确认删除？</p>
                  </div>
                </template>
                <t-link theme="danger" variant="outline" hover="color">删除</t-link>
              </t-popconfirm>
            </t-space>
          </template>
        </t-table>
      </div>
    </t-card>

    <!-- 产品入库 -->
    <product-warehousing ref="warehousing" :storeId="storeId" @refresh="getList"></product-warehousing>
    <!-- 产品出库 -->
    <product-outbound ref="outbound" :storeId="storeId" @refresh="getList"></product-outbound>
    <!-- 产品调拨 -->
    <product-dispatch ref="dispatch" :storeId="storeId" @refresh="getList"></product-dispatch>
    <!--产品盘点-->

    <!-- 填写出库信息 -->
    <product-config ref="config" from="detail" :storeId="storeId" @confirm="confirmProduct"></product-config>


  </div>
</template>

<script lang="jsx">
import {Input, Textarea} from 'tdesign-vue';
import {IconFont, CalendarIcon, BrowseIcon} from "tdesign-icons-vue";
import IconUAV from "@/components/icon-UAV/index.vue";
import ProductAdd from "@/pages/warehouse/product/add/index.vue";

import {
  warehouse_product_stockDeleteApi,
  warehouse_product_stockEditApi,
  warehouse_product_stockListApi
} from "@/api/warehouseInventory";
import {warehouseDetailApi, warehouseListApi} from "@/api/warehouse";
import {warehouse_orderCreateApi} from "@/api/InOutStorage";

import ProductWarehousing from "@/pages/inventory/components/product-warehousing/index.vue";
import ProductOutbound from "@/pages/inventory/components/product-outbound/index.vue";
import ProductDispatch from "@/pages/inventory/components/product-dispatch/index.vue";
import ProductConfig from "@/pages/inventory/components/product-outbound/product-config.vue";
import {outboundRecordCreateApi} from "@/api/inventory";

export default {
  name: 'Warehousing',
  components: {
    ProductConfig,
    ProductDispatch,
    ProductOutbound,
    ProductWarehousing,
    //ComOutbound,
    //ProductWarehousing,
    //ProductOutbound,
    //ProductAllot,
    //ProductInventory,
    //OrderInfo,
    IconUAV,
    IconFont,
    BrowseIcon,
    ProductAdd
  },
  data() {
    return {
      storeId: '', // 仓库ID
      storeInfo: {}, // 仓库详情
      storeList: [], // 仓库列表
      params: {
        page: 1,  // 当前页
        limit: 10,  // 每页条数
        warehouse_id: '', // 仓库ID
        product_id: '', // 产品ID
        product_classify_id: '', // 产品分类ID
        key: '',  // 关键字
        is_del: '', // 状态
      },

      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        {colKey: 'id', title: 'ID', align: 'center', width: 60,},
        {colKey: 'product_thumb', title: '图片', align: 'center', width: 80,},
        {colKey: 'product_title', title: '产品', width: 220, ellipsis: true},
        //{colKey: 'sn', title: 'SN', width: 220},
        {colKey: 'quantity', title: '库存', align: 'center', width: 120},
        //{colKey: 'unit_price', title: '入库价', width: 140},
        {colKey: 'total_price', title: '库存金额', width: 120},
        {colKey: 'product_selling_price', title: '售价', width: 120},
        {colKey: 'unit_title', title: '单位', width: 120},
        {
          colKey: 'remark', title: '备注', ellipsis: true, width: 180,
          edit: {
            component: Textarea,
            props: {
              clearable: true,
              autofocus: true,
              maxLength: 140,
            },
            // 透传给 component: Input 的事件
            on: (editContext) => ({
              onBlur: () => {
                this.handleEdit(editContext)
              },
            }),
          }
        },
        {colKey: 'option', title: 'title-slot-option', fixed: 'right', width: 160},
      ],
      selectedRowKeys: [],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
      },
      maxHeight: 472,
      loading: false,

      is_delOptions: [
        //(1 回收站, 0 正常)
        {label: '正常', value: 0},
        {label: '回收站', value: 1},
      ],

      editId: '',
      visible: false,
      warehouseList: [],
      warehouseName: '',
      info: {}
    };
  },
  mounted() {
    let height = document.documentElement.clientHeight - 244;
    this.maxHeight = height
    window.onresize = () => {
      // 获取屏幕高度 - 顶部高度
      height = document.documentElement.clientHeight - 244;
      this.maxHeight = height
    };

    const {storeId} = this.$route.query
    this.storeId = storeId
    this.params.warehouse_id = storeId
    this.getStoreInfo()
    this.getStoreList()

    this.getData()
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    // 获取仓库信息
    getStoreInfo() {
      warehouseDetailApi(this.storeId).then(res => {
        this.storeInfo = res.data

        console.log('storeInfo', this.storeInfo)
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 获取仓库列表
    getStoreList() {
      const params = {page: 1, limit: 9999}
      warehouseListApi(params).then(res => {
        this.storeList = res.data.map(item => ({...item, label: item.name, value: item.id}))
      })
    },
    // 切换仓库
    changeStore(item) {
      this.storeId = item.id
      this.params.warehouse_id = item.id

      this.getStoreInfo()
      this.getData()
    },
    // 编辑备注
    handleEdit(context) {
      const params = {
        id: context.editedRow.id,
        sort: context.editedRow.sort, // 排序
        remark: context.editedRow.remark
      }
      warehouse_product_stockEditApi(context.editedRow.id, params).then(res => {
        this.$message.success('编辑成功')
        this.getList()
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 前往仓库详情
    goStoreDetail() {
      this.$router.push({
        name: 'StoreDetail',
        query: {
          storeId: this.storeId
        }
      })
    },
    // 点击操作项
    handleOption(name) {
      this.$router.push({
        name: name,
        query: {
          storeId: this.storeId
        }
      })
    },
    // 入库
    handleWarehousing() {
      this.$refs.warehousing.open()
    },
    // 出库
    handleOutbound() {
      this.$refs.outbound.open()
    },
    // 调拨
    handleAllocation() {
      this.$refs.dispatch.open()
    },
    // 盘点
    handleInventory() {
      //this.$refs.inventory.open(3)
    },
    handleInfo(row) {
      this.$router.push({
        name: 'ProductInfo',
        query: {
          prodId: row.id,
        }
      })
    },
    // 出库
    onOutbound(row) {
      const data = {...row}
      data.title = data.product_title
      this.$refs.config.open(data)
    },
    // 确认出库产品
    confirmProduct(list, prodId) {
      const params = {
        ck_warehouse_id: list[0].ck_warehouse_id, // 出库ID 必需
        rk_warehouse_id: list[0].rk_warehouse_id, // 入库ID 必需
        batch_no: '', // 批次编号 可选
        product_data: JSON.stringify(list),
      }
      outboundRecordCreateApi(params).then(res=> {
        this.$message.success('出库成功')
        this.getList()
      }).catch(err=> {
        console.log('err', err)
      })
    },
    // 确认出库
    confirmOutbound(row) {
      const params = {
        order_type: 1, // 必需 订单类型（0入库；1出库；2调拨；3盘点）
        warehouse_id: this.storeId, // 必需 出/入仓库ID（调拨时：调入仓库ID）
        next_warehouse_id: '', // 可选 调出仓库ID（调拨时需要填写）
        order_date: this.$dayjs().format('YYYY-MM-DD'), // 必需 订单日期（yyyy-MM-dd）
        order_no: '', // 可选  单号（空值时系统生成）
        discount_amount: '', // 可选 总优惠金额（两位小数）
        linkman: '', // 联系人 可选
        phone: '', // 联系电话 可选
        operator_name: '', // 经办人 可选
        batch_no: '', // 批次编号 可选
        product_data: [{
          product_id: row.product_id, // 产品ID
          unit_id: row.unit_id,  // 单位ID
          quantity: row.quantity, // 数量两位小数
          is_sn: row.is_sn, // 开启SN序列号（0关闭；1开启）
          sn: row.sn, // SN数据
          unit_price: row.unit_price, // 含税单价（进货价）
          remark: row.remark, // 备注（50个字内）
        }], // 可选产品清单(JSON数据）
        remark: '', // 备注
      }
      params.product_data = JSON.stringify(params.product_data)
      warehouse_orderCreateApi(params).then(res => {
        this.$message.success(`出库成功`)
        this.getList()
      }).catch(err => {
        console.log(err)
      })
    },
    // 删除
    handleDelete(evt, row) {
      warehouse_product_stockDeleteApi({id: row.id}).then(res => {
        this.$message.success('删除成功')
        this.getList()
      }).catch(err => {
        console.log('err', err)
      })
    },
    // 获取数据
    getData() {
      this.pagination.defaultCurrent = 1
      this.getList()
    },
    // 获取列表
    getList() {
      this.loading = true
      this.params.page = this.pagination.defaultCurrent
      warehouse_product_stockListApi(this.params).then(res => {
        this.pagination.total = res.count
        this.lists = res.data
      }).catch(err => {
      }).finally(() => {
        this.loading = false
      })
    },
    // 切换分页
    pageChange(pageInfo) {
      const {current, defaultCurrent, defaultPageSize,} = pageInfo
      this.pagination.defaultCurrent = current
      this.getList()
    },
    handleSelectChange(value, {selectedRowData}) {
      this.selectedRowKeys = value;
    },
  },
}
</script>

<style lang="less" scoped>
.book-detail {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: var(--td-radius-medium);
  background-color: #FFFFFF;
}

.item-title {
  font-weight: 500;
}

.item-sn {
  font-size: 14px;
  font-weight: 400;
  line-height: 24px;
  text-align: left;
  color: rgba(0, 0, 0, 0.6);
}

/deep/ .content-card {

  .t-card__header {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingLR-xl);
    padding-bottom: 0;
  }

  .t-card__body {
    padding: var(--td-comp-paddingTB-l) var(--td-comp-paddingLR-xl) var(--td-comp-paddingTB-m);
  }

  .card-sub-title {
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    text-align: left;
    color: #000000;
    padding-top: 8px;
  }

  .setting-btn {
    font-size: 14px;
    font-weight: 400;
    line-height: 19.6px;
    text-align: left;
    color: #005687;
  }

  .invite-btn {
    font-size: 12px;
    font-weight: 400;
    line-height: 16.8px;
    text-align: left;
    color: #005687;

    background-color: #F3FBFF;
    border: 1px solid #005687;
    border-radius: var(--td-radius-default);
  }
}

/deep/ .action-btn {
  width: 126px;
  height: 42px;
  font-size: 16px;
  font-weight: 600;
  line-height: 22.4px;
  text-align: left;
  color: #FFFFFF;

  .t-button__text {
    display: flex;
    align-items: center;
    justify-content: center;

    i {
      z-index: 2;
      font-size: 12px;
      font-weight: bold;
      margin-right: 6px;

      &:after {
        position: absolute;
        display: inline-block;
        content: '';
        top: 50%;
        left: 50%;
        width: 14px;
        height: 14px;
        z-index: -1;
        background-color: #FFFFFF;
        border-radius: var(--td-radius-round);
        transform: translateX(-50%) translateY(-50%);
      }
    }
  }
}

.action-btn1 {
  background-color: #14A54E;
  border: 1px solid #14A54E;

  i {
    color: #14A54E;
  }
}

.action-btn2 {
  background-color: #FF5C46;
  border: 1px solid #DFE3E7;
}

.action-btn3 {
  background-color: #565656;
  border: 1px solid #DFE3E7;
}

.action-btn4 {
  color: black;
  background-color: #F9F9F9;
  border: 1px solid #E1E1E1;
}

/deep/ .filter {
  padding-top: 13px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .t-input, .t-input.t-is-readonly {
    //background-color: #F8F8F8;
  }
}

//.import-btn {
//  width: 69px;
//  color: #000000;
//  font-size: 14px;
//  font-weight: 400;
//  line-height: 19.6px;
//  background-color: #F9F9F9;
//  border: 1px solid #E1E1E1;
//}

.income {
  color: #14A54E;
  display: flex;
  align-items: center;

  i {
    width: 17px;
    height: 17px;
    color: #FFFFFF;
    font-size: 12px;
    display: flex;
    margin-left: 8px;
    align-items: center;
    justify-content: center;
    background-color: #14A54E;
    border-radius: var(--td-radius-small);
  }
}

.expenditure {
  color: #FF5C46;
  display: flex;
  align-items: center;

  i {
    width: 17px;
    height: 17px;
    color: #FFFFFF;
    font-size: 12px;
    display: flex;
    margin-left: 8px;
    align-items: center;
    justify-content: center;
    background-color: #FF5C46;
    border-radius: var(--td-radius-small);
  }
}

.footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #F9F9F9;
  padding: var(--td-comp-paddingTB-m) var(--td-comp-paddingLR-xl);
  padding-right: var(--td-comp-paddingLR-xxl);
}
</style>
